package com.guli.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guli.common.utils.R;
import com.guli.common.vo.AttrEsModel;
import com.guli.common.vo.SkuEsModel;
import com.guli.gulimall.product.config.GulimallEsConfig;
import com.guli.gulimall.product.dao.*;
import com.guli.gulimall.product.entity.*;
import com.guli.gulimall.product.entity.to.MemberPriceTo;
import com.guli.gulimall.product.entity.to.SkuFullReductionTo;
import com.guli.gulimall.product.entity.to.SkuLadderTo;
import com.guli.gulimall.product.entity.to.SpuBoundsTo;
import com.guli.gulimall.product.entity.vo.*;
import com.guli.gulimall.product.feign.CouponFeignService;
import com.guli.gulimall.product.feign.SearchFeignService;
import com.guli.gulimall.product.service.*;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescDao spuInfoDescDao;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private ProductAttrValueDao productAttrValueDao;

    @Autowired
    private SkuInfoDao skuInfoDao;

    @Autowired
    private SkuSaleAttrValueDao skuSaleAttrValueDao;

    @Autowired
    private SearchFeignService searchFeignService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandDao brandDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void addSpu(SpuInfoVo spuInfoVo) {
        // 1.pms_spu_info spu的基本信息表
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVo, spuInfoEntity);
        //赋值缺少的时间
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        baseMapper.insert(spuInfoEntity);
        // 2.pms_spu_info_desc 商品的介绍图集表
        List<String> decript = spuInfoVo.getDecript();
        if (decript != null) {
            String imgs = "";
            for (String s : decript) {
                imgs += ";" + s;
            }
            imgs = imgs.substring(1);
            SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
            descEntity.setSpuId(spuInfoEntity.getId());
            descEntity.setDecript(imgs);
            spuInfoDescDao.insert(descEntity);
        }
        // 3.pms_spu_images 商品的左上角小图
        List<String> images = spuInfoVo.getImages();
        if (images != null) {
            List<SpuImagesEntity> collect = images.stream().map(imgUrl -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgUrl(imgUrl);
                return spuImagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(collect);
        }
        // 4.pms_product_attr_value 页面中做添加的所有的规格信息
        List<BaseAttrs> baseAttrs = spuInfoVo.getBaseAttrs();
        if (baseAttrs != null) {
            List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                productAttrValueEntity.setAttrId(attr.getAttrId());
                productAttrValueEntity.setAttrValue(attr.getAttrValues());

                AttrEntity attrEntity = attrDao.selectById(attr.getAttrId());
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                productAttrValueEntity.setQuickShow(attr.getShowDesc());
                productAttrValueEntity.setSearchType(attrEntity.getSearchType());

                return productAttrValueEntity;
            }).collect(Collectors.toList());
            // 批量添加
            productAttrValueService.saveBatch(collect);
        }
        // 9.sms_spu_bounds spu的积分表
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        Bounds bounds = spuInfoVo.getBounds();
        if (bounds != null) {
            spuBoundsTo.setBuyBounds(bounds.getBuyBounds());
            spuBoundsTo.setGrowBounds(bounds.getGrowBounds());
        }
        couponFeignService.saveSpuBounds(spuBoundsTo);

        // -----------sku
        List<Skus> skus = spuInfoVo.getSkus();
        if (skus != null) {
            for (Skus sku : skus) {
                // 5.pms_sku_info 商品sku的基本信息
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                //销量
                skuInfoEntity.setSaleCount(0L);
                // 默认图片
                List<Images> imagesList = sku.getImages();
                if (imagesList != null) {
                    Images img = imagesList.stream().filter(item ->
                            item.getDefaultImg().equals(1)
                    ).findFirst().get();
                    skuInfoEntity.setSkuDefaultImg(img.getImgUrl());
                }
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSkuDesc(spuInfoEntity.getSpuDescription());
                skuInfoDao.insert(skuInfoEntity);
                // 6.pms_sku_images 商品sku的图片(一个sku多张图片)
                List<Images> images1 = sku.getImages();
                if (images1 != null) {
                    List<SkuImagesEntity> collect = images1.stream().filter(item ->
                            StringUtils.isNotEmpty(item.getImgUrl())
                    ).map(item -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        skuImagesEntity.setDefaultImg(item.getDefaultImg());
                        skuImagesEntity.setImgUrl(item.getImgUrl());
                        return skuImagesEntity;
                    }).collect(Collectors.toList());
                    //批量添加
                    skuImagesService.saveBatch(collect);
                }
                // 7.pms_sku_sale_attr_value sku的销售属性表
                List<Attr> attrList = sku.getAttr();
                if (attrList != null) {
                    List<SkuSaleAttrValueEntity> collect = attrList.stream().map(attr -> {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                        AttrEntity attrEntity = attrDao.selectById(attr.getAttrId());
                        skuSaleAttrValueEntity.setSearchType(attrEntity.getSearchType());
                        skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());

                        return skuSaleAttrValueEntity;
                    }).collect(Collectors.toList());

                    skuSaleAttrValueService.saveBatch(collect);
                }
                // ------------优惠券数据库
                // 8.sms_sku_ladder sku的打折信息表
                SkuLadderTo skuLadderTo = new SkuLadderTo();
                skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
                skuLadderTo.setAddOther(sku.getCountStatus());
                skuLadderTo.setFullCount(sku.getFullCount());
                skuLadderTo.setDiscount(sku.getDiscount());
                couponFeignService.saveSkuLadder(skuLadderTo);
                // 10.sms_sku_full_reduction sku的满减表
                SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();
                skuFullReductionTo.setSkuId(skuInfoEntity.getSkuId());
                skuFullReductionTo.setFullPrice(sku.getFullPrice());
                skuFullReductionTo.setReducePrice(sku.getReducePrice());
                skuFullReductionTo.setAddOther(sku.getPriceStatus());
                couponFeignService.saveSkuFullReduction(skuFullReductionTo);
                // 11.sms_member_price 会员等级价格表
                List<MemberPrice> memberPrice = sku.getMemberPrice();
                if (memberPrice != null) {
                    List<MemberPriceTo> collect = memberPrice.stream().map(item -> {
                        MemberPriceTo memberPriceTo = new MemberPriceTo();
                        memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                        memberPriceTo.setMemberLevelId(item.getId());
                        memberPriceTo.setMemberLevelName(item.getName());
                        memberPriceTo.setMemberPrice(item.getPrice());
                        return memberPriceTo;
                    }).collect(Collectors.toList());
                    couponFeignService.saveBatchMemberPrice(collect);
                }
            }
        }
    }

    //专高五批量上架
    @Override
    public R up(Long id) {
        try {
            // 先从数据库查询商品信息
            SpuInfoEntity spuInfoEntity = baseMapper.selectById(id);
            // 1.1查询需要检索的规格参数
            QueryWrapper<ProductAttrValueEntity> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("search_type", "1");
            wrapper1.eq("spu_id", id);
            List<ProductAttrValueEntity> baseAttrList = productAttrValueService.list(wrapper1);
            List<SkuEsVo.AttrVo> baseAttrs = new ArrayList<>();
            if (baseAttrList != null) {
                baseAttrs = baseAttrList.stream().map(attr -> {
                    SkuEsVo.AttrVo attrVo = new SkuEsVo.AttrVo();
                    attrVo.setAttrId(attr.getAttrId());
                    attrVo.setAttrName(attr.getAttrName());
                    attrVo.setAttrValue(attr.getAttrValue());
                    return attrVo;
                }).collect(Collectors.toList());
            }

            QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("spu_id", id);
            List<SkuInfoEntity> skuList = skuInfoDao.selectList(wrapper);
            //为了减少es的io次数 批量添加
            BulkRequest request = new BulkRequest();
            if (skuList != null) {
                for (SkuInfoEntity item : skuList) {
                    SkuEsVo skuEsVo = new SkuEsVo();
                    // 品牌
                    BrandEntity brandEntity = brandDao.selectById(spuInfoEntity.getBrandId());
                    skuEsVo.setBrandId(spuInfoEntity.getBrandId());
                    skuEsVo.setBrandImg(brandEntity.getLogo());
                    skuEsVo.setBrandName(brandEntity.getName());
                    //分类
                    CategoryEntity categoryEntity = categoryDao.selectById(spuInfoEntity.getCatalogId());
                    skuEsVo.setCatalogId(spuInfoEntity.getCatalogId());
                    skuEsVo.setCatalogName(categoryEntity.getName());
                    // feign调用库存服务 todo
                    skuEsVo.setHasStock(true);
                    skuEsVo.setHotScore(0L);
                    skuEsVo.setSaleCount(item.getSaleCount());
                    skuEsVo.setSkuId(item.getSkuId());
                    skuEsVo.setSpuId(item.getSpuId());
                    skuEsVo.setSkuTitle(item.getSkuTitle());
                    skuEsVo.setSkuImg(item.getSkuDefaultImg());
                    skuEsVo.setSkuPrice(item.getPrice());
                    //赋值规格参数
                    QueryWrapper<SkuSaleAttrValueEntity> wrapper2 = new QueryWrapper<>();
                    wrapper.eq("search_type", "1");
                    wrapper.eq("sku_id", item.getSkuId());
                    List<SkuSaleAttrValueEntity> saleAttrList = skuSaleAttrValueService.list(wrapper2);
                    if (saleAttrList != null) {
                        List<SkuEsVo.AttrVo> saleAttrs = saleAttrList.stream().map(attr -> {
                            SkuEsVo.AttrVo attrVo = new SkuEsVo.AttrVo();
                            attrVo.setAttrId(attr.getAttrId());
                            attrVo.setAttrName(attr.getAttrName());
                            attrVo.setAttrValue(attr.getAttrValue());
                            return attrVo;
                        }).collect(Collectors.toList());
                        baseAttrs.addAll(saleAttrs);
                    }
                    skuEsVo.setAttrs(baseAttrs);
                    request.add(new IndexRequest("product").id(skuEsVo.getSkuId().toString())
                            .source(JSONObject.toJSONString(skuEsVo), XContentType.JSON));
                }
                client.bulk(request, GulimallEsConfig.COMMON_OPTIONS);
                // 改商品状态
                spuInfoEntity.setPublishStatus(1);
                baseMapper.updateById(spuInfoEntity);
            }
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    //专高六批量上架
    @Override
    public R upSix(Long spuId) throws IOException {
        List<AttrEsModel> spuAttrs = productAttrValueDao.getSpuAttrValues(spuId);
        //根据spuId查出所有需要上架的商品
        List<SkuEsModel> skuEsModelList = skuInfoDao.getSkuEsModels(spuId);
        //遍历每个商品赋值属性
        for (SkuEsModel skuEsModel : skuEsModelList) {
            // 根据skuId查询自己的属性 使用set完成sku和spu去重
            Set<AttrEsModel> skuAttrs = skuSaleAttrValueDao.getSkuAttrValues(skuEsModel.getSkuId());
            skuAttrs.addAll(spuAttrs);
            // 将属性赋值给sku
            skuEsModel.setAttrs(new ArrayList<>(skuAttrs));
        }
        //feign调用上架
        R r = searchFeignService.upProduct(skuEsModelList);
        if (Integer.parseInt(r.get("code").toString()) == 0) {
            return r.ok();
        }
        return R.error();
    }
}